package rpc;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.UUID;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeoutException;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: LianBao
 * Date: 2025-03-26
 * Time: 20:09
 */
public class Client {
    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        //1. 建立连接(Connection)
        ConnectionFactory connectionFactory = new ConnectionFactory();
        //设置连接参数:ip,端口号,用户名,密码,虚拟机
        connectionFactory.setHost("116.205.165.92");//ip
        connectionFactory.setPort(5672);//端口号,默认是5672
        connectionFactory.setUsername("Test");//用户名
        connectionFactory.setPassword("123");//密码
        connectionFactory.setVirtualHost("TestVirtualHost");//设置操作的虚拟机
        Connection connection = connectionFactory.newConnection();//从连接工厂中获取到连接

        //2. 开启通道(Channel)
        Channel channel = connection.createChannel();//通过connection开启通道

        String msg = "HelloRPC";
        String correlationId = UUID.randomUUID().toString();
        //
        channel.queueDeclare("RPC_RESPONSE_QUEUE",true,false,false,null);
        channel.queueDeclare("RPC_REQUEST_QUEUE",true,false,false,null);

        //发送请求
        AMQP.BasicProperties properties = new AMQP.BasicProperties().builder()
                .correlationId(correlationId)//设置correlationId
                .replyTo("RPC_RESPONSE_QUEUE")//设置响应的队列
                .build();
        channel.basicPublish("", "RPC_REQUEST_QUEUE", properties, msg.getBytes());

        //使用阻塞队列,来存储响应信息
        final BlockingQueue<String> response = new LinkedBlockingQueue<>(1);
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String responseMsg = new String(body);
                System.out.println("接收到回调消息" + responseMsg);
                if (correlationId.equals(properties.getCorrelationId())) {
                    //如果correlationId相等,把消息放进阻塞队列中
                    response.offer(responseMsg);
                }
            }
        };
        channel.basicConsume("RPC_RESPONSE_QUEUE", true, consumer);

        //从阻塞队列中
        System.out.println("响应结果"+response.take());


        //6.释放资源
        channel.close();
        connection.close();

    }
}
